package com.example.demo.bizhan.classloader;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.*;

/**
 * @description: xxx
 * @time: 2020-10-29 20:35
 * @author: baojinlong
 * 自定义的ClassLoader:使用自定义的ClassLoader到指定的目录下面文件中加载.class文件
 **/
public class PKClassLoader extends ClassLoader {
    private String path;
    private String classLoaderName;

    public PKClassLoader(String path, String classLoaderName) {
        this.path = path;
        this.classLoaderName = classLoaderName;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }

    /**
     * 加载指定.class文件到系统中
     *
     * @param name
     * @return
     */
    private byte[] loadClassData(String name) {
        String fileName = path + name + ".class";
        try (InputStream inputStream = new FileInputStream(new File(fileName)); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            int i;
            while ((i = inputStream.read()) != -1) {
                byteArrayOutputStream.write(i);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[0];
    }
}
